
package com.rainbow.common.handler.config;

import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.rainbow.common.core.toolkit.SpringBeanUtil;
import com.rainbow.common.handler.auth.AuthInterceptor;
import com.rainbow.common.handler.properties.HandleProperties;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 配置拦截器
 *
 * @author 付为地
 */
@Configuration
@EnableConfigurationProperties(HandleProperties.class)
public class WebMvcConfig implements WebMvcConfigurer {

    @Resource
    private HandleProperties handleProperties;

    /**
     * 配置CORS跨域支持
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowCredentials(true)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS").maxAge(3600);
    }

    /**
     * 添加interceptor,
     * 默认添加鉴权认证
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        if (ObjectUtils.isNotEmpty(handleProperties) && Objects.equal(true, handleProperties.getAuth().isEnable())) {
            AuthInterceptor authInterceptor = SpringBeanUtil.getBean(AuthInterceptor.class);
            if (ObjectUtils.isNotEmpty(authInterceptor)) {
                List<String> includePaths = Lists.newArrayList("/**");
                List<String> excludePaths = Lists.newArrayList("/actuator/**","/feign/warmUp");
                if (ObjectUtils.isNotEmpty(handleProperties.getAuth().getIncludes())) {
                    includePaths.addAll(handleProperties.getAuth().getIncludes());
                    includePaths = includePaths.stream().filter(ObjectUtils::isNotEmpty).distinct().collect(Collectors.toList());
                }
                if (ObjectUtils.isNotEmpty(handleProperties.getAuth().getExcludes())) {
                    excludePaths.addAll(handleProperties.getAuth().getExcludes());
                    excludePaths = excludePaths.stream().filter(ObjectUtils::isNotEmpty).distinct().collect(Collectors.toList());
                }
                registry.addInterceptor(authInterceptor)
                        .addPathPatterns(includePaths)
                        .excludePathPatterns(excludePaths);
            }
        }
    }
}
